//*********基础功能重新封装**************//
var openAnimation = false;
var openDelay = 0;

function goto(url,data){
    //把传递的参数保存到本地
    setData4Page(url,data)
    //showLoading()
    if (1 == AppCodeEnv ) {
        gotoServer(url)
    }else {
        gotoLocal(url)
    }
}

function gointo(url,data) {
    goto(url,data);
    setTimeout(function () {
        api.closeWin({name:"page"+windowName});
    },1000)
}

function gotoServer(url){
    //把传递的参数保存到本地
    try{
        var dev;if (AppDevEvn == 1) {dev = "?t=" + Math.random()}else{dev = "";}
        var PageUrl = pageApi + "/ApiCloud/Page/" + AppClientName + "/" + url + ".html" + dev;
        var param = {
            name: "page"+url,
            url: PageUrl,
            bgColor: "#FFF",
        }
        if (isTrue(openAnimation)) {
            param['animation'] = openAnimation
        }else {
            param['animation'] = {
                type:"push",                //动画类型（详见动画类型常量）
                subType:"from_right",       //动画子类型（详见动画子类型常量）
                duration:400                //动画过渡时间，默认300毫秒
            }
        }
        if (isTrue(openDelay)) {
            param['delay'] = openDelay
        }
        api.openWin(param);
    }catch(e){
        return false;
    }finally{
        return true;
    }
}

function gotoLocal(url){
    //把传递的参数保存到本地
    try{
        var dev;if (AppDevEvn == 1) {dev = "&t=" + Math.random()}else{dev = "";}
        var PageUrl = url + ".html"+ dev;
        api.openWin({
            name: "page"+url,
            url: PageUrl,
            bgColor: "#FFF",
            // pageParam: {
            //     name: 'test'
            // }
            animation:{
                type:"push",                //动画类型（详见动画类型常量）
                subType:"from_right",       //动画子类型（详见动画子类型常量）
                duration:400                //动画过渡时间，默认300毫秒
            }
        });
        // appcan.window.open({
        //     name:"page"+url,
        //     data:PageUrl,
        //     dataType:0,
        //     type:0,
        //     //aniId:0,
        //     aniId:2,
        //     animDuration:300,
        //     extraInfo:{}
        // });
    }catch(e){
        return false;
    }finally{
        return true;
    }
}

function gotoWeb(url) {
    // appcan.window.open({
    //     name:"page"+url,
    //     data:url,
    //     dataType:0,
    //     type:0,
    //     aniId:2,
    //     animDuration:300,
    //     extraInfo:{}
    // });
}

function goback(){
    // appcan.window.windowBack(1,200);
    api.closeWin();
}
function gobackDelay(delay){
    if (delay == undefined) {
        delay = 500;
    }
    setTimeout(function () {
        api.closeWin();
    },delay);
}

function close(){
    // appcan.window.close(2,200);
    api.closeWin();
}
//把传递的参数保存到本地
function setData4Page(name,data){
    log("把传递的参数保存到本地")
    log("data")
    log(data)
    var DataPage;
    if(data == {}){
        DataPage = {};
    }else{
        DataPage = data;
    }
    if(typeof DataPage != "string"){
        var str = JSON.stringify(DataPage)
    }else{
        var str = ""
    }
    setLocData("DataPage" + AppClientName + name ,str );
}

//取出其他页面保存到本页面的参数
function getData4Page(name){
    log("start getData4Page")
    if(typeof name == "undefined" ){
        if(typeof  windowName == "undefined" ){
            return false
        }else{
            name = windowName;
        }
    }


    var data =  getLocData("DataPage" + AppClientName + name);
    //取出数据就清空原来的数据
    setData4Page(name,{});
    log(data);
    log(typeof data);
    try{
        var d = JSON.parse(data);
    }catch(e){
        return data;
    }finally{
        //do nothing;
    }

    log("end getData4Page")
    return d;
}

function showToast(text){
    api.toast({
        msg: text
    });
}
function showWarning(text){
   Page.warning.message = text
   Page.warning.open = true
}

function hideToast(){
    // appcan.window.closeToast();
}

function showConfirm (message,functionConfirm,functionCancel) {
    api.confirm({
        title: '提示',
        msg: message,
        buttons: ['确定', '取消']
    }, function(ret, err) {
        var index = ret.buttonIndex;
        if(index == 1){
            //点击确定
            functionConfirm();

            log("functionConfirm");
        }else if(index == 2){
            //点击取消

            log("functionCancel");
            functionCancel();
        }else{
            alert("应用发生位置错误，可以尝试的操作有：1.重新登陆；2.重新安装应用")
        }
    });
}

function disablePullDownRefresh(){
    // appcan.window.disableBounce();
}
function enablePullDownRefresh(){
    // appcan.window.enableBounce();
}

var WindowLoading
function showLoading() {
    // WindowLoading = MuseUILoading()
    Page.loading = true;
    setTimeout(hideLoading,10000)
}
function hideLoading() {
    // logJson(WindowLoading,"test WindowLoading:")
    // if (WindowLoading !== undefined) {WindowLoading.close();}

    Page.loading = false;
}


//下拉刷新
// function onPullDownRefresh(func){
//     Page.OnPullDownRefresh = func
//     Page.PageRefreshing = true;
//
// }
//停止下拉刷新
function startPullDownRefresh(){
    Page.PageRefreshing = true;
}
function stopPullDownRefresh(){
    Page.PageRefreshing = false;
    api.refreshHeaderLoadDone();
}

//上拉加载
// function onPullUpLoadMore(func){
//     Page.OnPullUpLoadMore = func
//     Page.PageLoadingMore = true;
// }
function startPullUpLoadMore(){
    Page.PageLoadingMore = true;
}
//停止下拉刷新
function stopPullUpLoadMore(){
    Page.PageLoadingMore = false;
}
function clearLoading() {
    Page.PageLoadingMore = false;
    Page.PageRefreshing = false;
    Page.loading = false;
    Page.listLoading = false;
}

//进入前台
function onWindowShow(func){
    //clearLoading();
    api.addEventListener({
        name:'viewappear'
    }, function(ret, err){
        // alert('应用回到后台');
        func()
    });
}

//进入后台
function onWindowHide(func){
    api.addEventListener({
        name:'viewdisappear'
    }, function(ret, err){
        // alert('应用回到后台');
        func()
    });
}

function setOpenAnimFromBottom() {
    openAnimation = {
        type:"push",                //动画类型（详见动画类型常量）
        subType:"from_bottom",       //动画子类型（详见动画子类型常量）
        duration:200                //动画过渡时间，默认300毫秒
    }
}
function setOpenAnimFromLeft() {
    openAnimation = {
        type:"push",                //动画类型（详见动画类型常量）
        subType:"from_left",       //动画子类型（详见动画子类型常量）
        duration:200                //动画过渡时间，默认300毫秒
    }
}
function setOpenAnimFromRight() {
    openAnimation = {
        type:"push",                //动画类型（详见动画类型常量）
        subType:"from_right",       //动画子类型（详见动画子类型常量）
        duration:200                //动画过渡时间，默认300毫秒
    }
}
function setOpenAnimFade() {
    openAnimation = {
        type:"fade",                //动画类型（详见动画类型常量）
        duration:200                //动画过渡时间，默认300毫秒
    }
}
function setOpenDelay(time) {
    openDelay = time
}

//下拉刷新
function onPullDownRefresh(func){
    api.setRefreshHeaderInfo({
        visible: true,
        loadingImg: '../image/loading_more.gif',
        bgColor: '#ffffff',
        textColor: '#333',
        textDown: '',
        textUp: '用力拽',
        showTime: true
    }, function(ret, err) {
        api.refreshHeaderLoading();
        func()
    });

}

/**
 * 上拉加载
 * @param func
 */
var index_onPullUpLoadMore = 0;
function onPullUpLoadMore(func){
    Page.PageHasLoadingMore = true;
    api.addEventListener({
        name:'scrolltobottom',
        extra:{threshold:0}
    }, function(ret, err){
        // log(getTimestampMs() - index_onPullUpLoadMore)
        if (getTimestampMs() - index_onPullUpLoadMore < 1000) {
            return false;
        }
        //上拉加载时需要加载的数据
        Page.PageLoadingMore = true
        setTimeout(function () {
            Page.PageLoadingMore = false
        },10000)
        func()

        //500ms内屏蔽再次调用，避免页面频繁操作
        index_onPullUpLoadMore = getTimestampMs();
    });
}

//向下滚动js部分
function onScrollDown(func ,offset) {
    if (offset === undefined) {
        offset = 1000
    }
    api.addEventListener({
        name:'swipeup'
    }, function(ret, err){
        var currScrollTop =  document.body.scrollTop;
        // if(currScrollTop == 0) currScrollTop = document.documentElement.scrollTop;
        if (currScrollTop > offset) {
            Page.showScroll = true
            func();
        }
    });
}
//向下滚动html配套
//     <div class="pos-f r9 b9 padb20" v-show="showScroll">
//     <div class="wh15-15 round bca04 fs16 c13 flcc pos-r op5">
//     <mu-button small @click="showScroll = !showScroll;scrollTo('banner')" fab color="darkBlack">
//     <mu-icon value="arrow_upward"></mu-icon>
//     </mu-button>
//     </div>
//     </div>


